package com.hc.java.random;

import java.security.SecureRandom;

/**
 * 生成12位随机字符串
 */
public class RandomStringGenerator {

    // 定义字符集：数字、大小写字母、常见特殊符号
    private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
    private static final String CHAR_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGIT = "0123456789";
    private static final String SPECIAL = "@#$%^&*_+-=[]{};:,.?";

    private static final String ALL_CHARS = CHAR_LOWER + CHAR_UPPER + DIGIT + SPECIAL;
    private static final int LENGTH = 12;

    private static final SecureRandom random = new SecureRandom();

    /**
     * 生成包含数字、字母、特殊符号的 12 位随机字符串
     * 确保每种类型至少出现一次
     */
    public static String generateRandomString() {
        StringBuilder sb = new StringBuilder(LENGTH);

        // 先确保每类字符至少有一个
        sb.append(randomChar(CHAR_LOWER));   // 1. 小写字母
        sb.append(randomChar(CHAR_UPPER));   // 2. 大写字母
        sb.append(randomChar(DIGIT));        // 3. 数字
        sb.append(randomChar(SPECIAL));      // 4. 特殊符号

        // 剩余 8 位从所有字符中随机选择
        for (int i = 4; i < LENGTH; i++) {
            sb.append(randomChar(ALL_CHARS));
        }

        // 打乱顺序，避免前4位固定类型
        return shuffleString(sb.toString());
    }

    // 随机从字符串中取一个字符
    private static char randomChar(String str) {
        return str.charAt(random.nextInt(str.length()));
    }

    // 打乱字符串顺序
    private static String shuffleString(String input) {
        char[] chars = input.toCharArray();
        for (int i = chars.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            char temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
        }
        return new String(chars);
    }

}